package com.tst.app.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.tst.app.conf.StsConfig;
import com.tst.app.vo.StsVo;

public class StsUtils {

    public static StsVo get() throws ClientException {
        StsVo stsVo = new StsVo();
        String endpoint = "sts.aliyuncs.com";
        String accessKeyId = StsConfig.getInstance().getAccessKeyId();
        String accessKeySecret = StsConfig.getInstance().getAccessKeySecret();
        String roleArn = StsConfig.getInstance().getRoleArn();
        String roleSessionName = "session-name";
        String policy = "{\n" +
                "    \"Version\": \"1\", \n" +
                "    \"Statement\": [\n" +
                "        {\n" +
                "            \"Action\": [\n" +
                "                \"oss:*\"\n" +
                "            ], \n" +
                "            \"Resource\": [\n" +
                "                \"acs:oss:*:*:*\" \n" +
                "            ], \n" +
                "            \"Effect\": \"Allow\"\n" +
                "        }\n" +
                "    ]\n" +
                "}";
        // 添加endpoint（直接使用STS endpoint，前两个参数留空，无需添加region ID）
        DefaultProfile.addEndpoint("", "", "Sts", endpoint);
        // 构造default profile（参数留空，无需添加region ID）
        IClientProfile profile = DefaultProfile.getProfile("", accessKeyId, accessKeySecret);
        // 用profile构造client
        DefaultAcsClient client = new DefaultAcsClient(profile);
        final AssumeRoleRequest request = new AssumeRoleRequest();
        request.setMethod(MethodType.POST);
        request.setRoleArn(roleArn);
        request.setRoleSessionName("123");
        request.setDurationSeconds(3600L);
//        request.setPolicy(policy); // Optional
        final AssumeRoleResponse response = client.getAcsResponse(request);
        stsVo.setExpiration(response.getCredentials().getExpiration());
        stsVo.setSecurityToken(response.getCredentials().getSecurityToken());
        stsVo.setAccessKeyId(response.getCredentials().getAccessKeyId());
        stsVo.setAccessKeySecret(response.getCredentials().getAccessKeySecret());
        return stsVo;

    }
}
